#include "ReadFileAction.h"
#include "Config.h"

#include <fstream>

CReadFileAction::CReadFileAction(Client *aClient, HTTPRequestInfo *aRequestInfo, HTTPResponseHeaders *aResponseHeaders)
{
    mClient = aClient;
    mRequestInfo = aRequestInfo;
    mResponseHeaders = aResponseHeaders;
}


CReadFileAction::~CReadFileAction(void)
{

}

bool CReadFileAction::PrepareAction()
{
    // We're just going to read an HTML file so whatever.
    return true;
}
bool CReadFileAction::ExecuteAction()
{
    ifstream File("." + mRequestInfo->mResource, fstream::in | fstream::binary);

    if(!File.is_open())
    {
        cout << "Unable to open file ." << mRequestInfo->mResource << endl;
        //TODO: 404
        return false;
    }

    File.seekg(0, fstream::end);
    /** problem on unix? **/
    unsigned int Size = File.tellg();
    
    //cout << "Size of " << mRequestInfo->mResource << ": " << Size << endl;
    
    File.seekg(0, fstream::beg);

    char *buffer;

    buffer = new(nothrow) char [Size + 1];

    if(buffer == 0)
    {
        cout << "Unable to allocate memory!" << endl;
        return false;
    }

    cout << "Buffer memory position: " << &buffer << " Value: " << *buffer << endl;

    File.read(buffer, Size);
    
    File.close();

    (*mResponseHeaders) += pair<string, string>("Content-Length", StdToStr<unsigned int>(Size));

    mResponseHeaders->SetResponseCode(200, "OK", mRequestInfo->mVersion);

    mClient->Send(mResponseHeaders->ToString());

    mClient->SendBinary(buffer, Size);

    cout << "ReadFileAction " << Size << endl;

    delete [] buffer;
    
    return true;
}
bool CReadFileAction::CleanUp()
{
    cout << "Read File Action Quit." << endl;
    return true;
}

void CReadFileAction::SetFile(string File)
{

}
